<template>
  <div class="table-search">
    <el-form class="filter-box">
      <el-select
        v-model="searchForm.filterKey"
        size="mini"
        popper-class="select-popper"
        placeholder="搜索字段"
        class="filter-key"
        @change="seachFilterChange"
      >
        <el-option 
          v-for="item in filterList" 
          :key="item.field" 
          :label="item.name" 
          :value="item.field"
        />
      </el-select>
      <el-date-picker
        v-if="searchForm.filterType === 'date'"
        v-model="searchForm.searchVal"
        type="daterange"
        size="mini"
        placeholder="选择日期"
        class="filter-val"
        range-separator="-"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        value-format="yyyy-MM-dd"
        @change="searchChange"
      />
      <el-date-picker
        v-else-if="searchForm.filterType === 'datetime'"
        v-model="searchForm.searchVal"
        type="datetimerange"
        size="mini"
        placeholder="选择时间"
        class="filter-val"
        range-separator="-"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        :picker-options="pickerOptions"
        value-format="yyyy-MM-dd HH:mm:ss"
        @change="searchChange"
      />
      <el-select
        v-else-if="searchForm.filterType === 'select'"
        v-model="searchForm.searchVal"
        size="mini"
        clearable
        popper-class="select-popper"
        placeholder="请选择筛选值…"
        class="filter-val"
        @change="searchChange"
      >
        <el-option 
          v-for="(item,index) in subFilterList" 
          :key="index" 
          :label="item.dictName" 
          :value="item.dictCode"
        />
      </el-select>
      <el-select
        v-else-if="searchForm.filterType === 'picklist'"
        v-model="searchForm.searchVal"
        size="mini"
        clearable
        popper-class="select-popper"
        filterable
        remote
        :remote-method="remoteSelections"
        placeholder="请输入筛选关键字…"
        class="filter-val"
        :default-first-option="true"
        :loading="loading"
        @change="searchChange"
      >
        <el-option 
          v-for="(item,index) in subFilterList"  
          :key="index" 
          :label="item.value" 
          :value="item.value" 
        />
      </el-select>
      <el-input
        v-else-if="searchForm.filterType === 'batch'"
        v-model="searchForm.searchVal"
        clearable
        size="mini"
        type="textarea"
        :rows="1"
        placeholder="输入搜索关键字"
        class="filter-val no-resize"
        @keyup.enter.native="searchList"
        :readonly="disabled"
        @change="searchChange"
      />
      <el-input
        v-else
        v-model="searchForm.searchVal"
        clearable
        size="mini"
        maxlength="50"
        placeholder="输入搜索关键字"
        class="filter-val"
        @keyup.enter.native="searchList"
        :readonly="disabled"
        @change="searchChange"
      />
      <el-button class="search-btn" type="primary" size="mini" :disabled="disabled" @click="searchList">查询</el-button>
      <!-- 收藏 -->
      <div v-if="showCustomCollect" class="filter-collect" @click="initCollectList">
        <el-button v-popover:latelyPopover class="collect-btn" placement="top-end">
          <i class="el-icon-star-on" />
          <i class="el-icon-caret-bottom" />
        </el-button>
        <el-popover
          ref="latelyPopover"
          v-model="popoverShow"
          popper-class="lately-popper-box"
          placement="bottom-start"
          trigger="click"
          :visible-arrow="false"
        >
          <div class="search-lately-item">
            <div v-for="(item,index) in collectFilters" :key="index" class="item" @click="addFilters(item.filterValue,item.resultsRaw)">
              {{ item.filterDescribe }}</div>
            <div class="item other" @click="openQuickFilter"><i class="el-icon-setting" />创建快速筛选</div>
          </div>
        </el-popover>
      </div>
    </el-form>
  </div>
</template>

<script>
import { parseTime} from '../lnk-combinefilter/utils'
import { setStore } from '../util/store'
import {
  remoteSearch,
  getDictByType,
  getCollectList
} from '../apis/table.data.js'

export default {
  name:'TableSearchBar',
  props: {
    filterList: {
      type: Array,
      default() {
        return []
      }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    showCustomCollect: {
      type: Boolean,
      default: false
    },
    hasDefaultSearch: {
      type: Boolean,
      default: true
    },
    searchDefault: {
      type: String,
      default: ''
    },
    /*表格索引*/
    tabIndex:{
      type:[String,Number],
      default:0
    },
    defaultSearch: {
      type: String,
      default: ''
    },
    // 查询参数类型
    paramType:{
      type:String,
      default:'filter', // filter为标准分页查询，json为普通json对象数据
    },
  },
  data() {
    return {
      popoverShow: false,
      collectFilters: [], // 收藏的查询条件
      searchForm: {
        searchVal: '',
        filterKey: '',
        filterType: 'text',
        optionRequest: '',
        isTrim:true
      },
      subFilterList: [],
      loading:false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  watch: {
    searchDefault(val) {
      if (this.hasDefaultSearch) {
        this.$set(this.searchForm, 'filterKey', val)
        setTimeout(() => {
          this.seachFilterChange(val)
        }, 100)
      }
    },
    filterList(val) {
      if (this.defaultSearch != '') {
        this.$set(this.searchForm, 'filterKey', this.defaultSearch)
        setTimeout(() => {
          this.seachFilterChange(this.defaultSearch)
        }, 100)
      }
    }
  },
  created() {
    if (this.showCustomCollect && !!this.$route.query.menuCode) {
      this.initCollectList()
    }
  },
  methods: {
    // 搜索字符串过滤
    stripscript(s) {
      var pattern = new RegExp(
        "[%`~!@#$^&*()=|{}':'\\[\\]<>/?~！@#￥……&*（）——|{}【】‘：”“'。？]",
      ) //格式 RegExp("[在中间定义特殊过滤字符]")
      var rs = ''
      for (var i = 0; i < s.length; i++) {
        if(pattern.test(s[i])){
          // rs = s.substr(i, 1).replace(pattern, 'Containing Illegal Characters')
          rs=encodeURI(s)
          //  rs=encodeURIComponent(s)
          console.log(s,'==',encodeURI(s),'====',encodeURIComponent(s))
          return rs
        }
        else{
          rs = s
        }
      }
      return rs
    },
    // 打开快速筛选
    openQuickFilter() {
      this.$emit('showCombineFilter', true)
    },
    initCollectList() {
      getCollectList(this.$route.query.menuCode,this.tabIndex).then(res => {
        this.collectFilters = res.data
      })
    },
    seachFilterChange(val) {
      const selectedObj = this.filterList.find((item) => item.field === val)
      const clearTypes=['date','datetime','select','picklist'] // 需清空输入值的类型
      
      // 非文本输入框类型时，清空搜索关键字，文本输入框保留搜索之
      if(!selectedObj || !selectedObj.type || clearTypes.includes(selectedObj.type) || selectedObj.type!=this.searchForm.filterType){
        this.searchForm.searchVal = ''
      }
      this.searchForm.isTrim =selectedObj  && selectedObj.isTrim!==false
      this.searchForm.optionRequest = ''
      this.subFilterList = []
      this.searchForm.filterType = (selectedObj && selectedObj.type) || 'text'
      switch (this.searchForm.filterType) {
        case 'select':
          if(selectedObj && selectedObj.lov){
            const dictList = selectedObj.lov.list
            if(dictList && dictList instanceof Array && dictList.length>0){
              this.subFilterList = dictList
            }else{
              getDictByType(selectedObj.lov).then(res => {
                this.subFilterList = res.data || []
                const lov=selectedObj.lov
                const dictName=`${lov.domainCode}_${lov.appCode}_${lov.dictTypeCode}`
                setStore({name: dictName, content: res.data || [], type: 'session'})
              })
            }
          }
          break
        case 'picklist':
          this.searchForm.optionRequest = (selectedObj && selectedObj.optionsRequest) || ''
          break
        default:
          break
      }
      this.searchChange()
    },
    searchChange(){
      const params={
        [this.searchForm.filterKey]:this.searchForm.searchVal
      }
      this.$emit('change',params)
    },
    searchList() {
      const searchData = []
      if (!this.searchForm.filterKey && this.searchForm.searchVal !== '') {
        this.$message({
          type: 'warning',
          message: `请选择筛选条件!`
        })
        return
      }
      
      if(this.paramType==='json'){
        const params={
          [this.searchForm.filterKey]:`${this.searchForm.searchVal || ''}`.trim()
        }
        this.$emit('get-search', params)
        this.$emit('tableSearch', 'search', params)
        return
      }
      if (this.searchForm.filterKey&&this.searchForm.searchVal) {
        let resValue = ''
        switch (this.searchForm.filterType) {
          case 'date':
              searchData.push({
                id: this.searchForm.filterKey,
                value: this.searchForm.searchVal[0] + ' 00:00:00',
                property: this.searchForm.filterKey,
                operator: '>='
              })

              searchData.push({
                id: this.searchForm.filterKey + '1',
                value: this.searchForm.searchVal[1] + ' 23:59:59',
                property: this.searchForm.filterKey,
                operator: '<='
              })
            break
          case 'datetime':
              searchData.push({
                id: this.searchForm.filterKey,
                value: this.searchForm.searchVal[0],
                property: this.searchForm.filterKey,
                operator: '>='
              })

              searchData.push({
                id: this.searchForm.filterKey + '1',
                value: this.searchForm.searchVal[1],
                property: this.searchForm.filterKey,
                operator: '<='
              })
            break
          case 'select':
          case 'equal':
          case 'picklist':
              resValue = this.searchForm.isTrim===false?this.searchForm.searchVal : this.searchForm.searchVal.trim()
              searchData.push({
                id: '',
                value: resValue,
                property: this.searchForm.filterKey,
                operator: '='
              })
            break
          case 'batch':
            const batchVal = this.searchForm.searchVal.trim().replaceAll('\\s{1,}', ',') || ''
            if(batchVal.indexOf(',') !== -1){
              searchData.push({
                id: '',
                value: `[${batchVal}]`,
                property: this.searchForm.filterKey,
                operator: 'in'
              })
            } else {
              resValue = this.searchForm.isTrim===false?this.searchForm.searchVal : this.searchForm.searchVal.trim()
              searchData.push({
                id: '',
                value: resValue.replace('\n', ''), //this.stripscript(this.searchForm.searchVal),
                property: this.searchForm.filterKey,
                operator: 'like'
              })
            }
            break
          default:
            resValue = this.searchForm.isTrim===false?this.searchForm.searchVal : this.searchForm.searchVal.trim()
            searchData.push({
              id: '',
              value:resValue,//this.stripscript(this.searchForm.searchVal),
              property: this.searchForm.filterKey,
              operator: 'like'
            })
            break
        }
      }      
      this.$emit('get-search', searchData)
      this.$emit('tableSearch', 'search', searchData)
    },
    addFilters(conditions,results) {
      this.popoverShow = false
      // this.$emit('collectFilter', { filtersraw:JSON.parse(conditions), results: JSON.parse(results) })
      const nowDate = parseTime(new Date(),'{y}-{m}-{d}')
      const filtersraw = JSON.parse(conditions)
      filtersraw.forEach(v=>{
        if(v.operator==='today'){
          // 处理条件为当天的数据
          v.value = nowDate
        }
      })
      const resultsRaw = JSON.parse(results)
      resultsRaw.forEach(v=>{
        if(v.condition==='today'){
          // 处理条件为当天的数据
          v.value = nowDate
        }
      })

      this.$emit('collectFilter', { filtersraw, results: resultsRaw })
    },
    remoteSelections(query) {
      if (query.trim() == '') {
        return
      }
      let rqUrl = this.searchForm.optionRequest
      rqUrl.indexOf('?') === -1 ? rqUrl = `${rqUrl}?value=${query}` : rqUrl = `${rqUrl}&value=${query}`
      this.loading = true
      remoteSearch(rqUrl).then(res => {
        this.subFilterList = res.data
        this.loading = false
      }).catch(()=>{
         this.loading = false
         this.subFilterList = []
      })
    }
  }
}

</script>

<style lang="scss" scoped>
@import "../../../../theme/qup-theme";
  .filter-box {
    display: flex;
    /deep/ .el-input__inner{
      border-color: $qup-table-border;
    }
    .filter-val.no-resize /deep/.el-textarea__inner {
      resize: none;
      min-height: 28px !important;
      height: 28px;
      border-radius: 0;
      border-left: 0;
      &:focus,&:hover {
        border-color: $qup-table-border !important;
      }
    }
    .input-with-select,
    .el-date-editor {
      display: inline-block;
      width: 215px;
      line-height: 1;

      /deep/ .el-input__inner {
        border-radius: 0;
        width: 215px !important;
        border-right: 0;
        line-height: 25px;
      }

      /deep/ .el-range__close-icon {
        position: absolute;
        right: -4px;
        top: 0;
      }
    }

    /deep/ .el-button {
      color: #fff;
      margin-left: -5px;
    }

    .el-select {
      /deep/ .el-input__inner {
        border-radius: 0;
        width: 100px;
      }
    }

    .filter-key /deep/ .el-input__inner {
      width: 120px !important;
      border-radius: 0;
      border-bottom-left-radius: 4px;
      border-top-left-radius: 4px;
    }

    .filter-val {
      width: 215px;
      /deep/ .el-input__inner {
        border-radius: 0;
        border-left: 0;
        border-right: 0;
        &:focus,
        &:hover {
          border-color: $qup-table-border !important;
        }
      }

      &.el-date-editor {
        width: atuo;
      }

      &.el-range-editor {
        border-radius: 0;
        border-right: 0;
        border-left: 0;
        width: 215px !important;
      }
      &.el-date-editor--datetimerange{
        width: 305px !important;
      }
    }

    .search-btn {
      font-size: 12px;
    }

    .filter-collect {
      margin-left: 10px;

      .collect-btn {
        background-color: #fff !important;
        border: 1px solid #ddd !important;
        color: #A6A6A6;
        font-size: 16px;
        padding: 5px 5px;
        height: 28px;

        .el-icon-caret-bottom {
          font-size: 14px;
        }
      }
    }

  }

</style>
